package com.adam.example.search;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import com.adam.example.ElasticsearchClientHolder;
import com.adam.example.types.Book;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;

public class RawJsonSearchExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient client = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();

        //raw json
        Reader reader = new StringReader("{\"query\": {\"term\": {\"title\": \"java\"}}}");
        SearchResponse<Book> searchResponse = client.search(builder -> builder
                .index("test_books")
                .withJson(reader), Book.class
        );
        reader.close();

        HitsMetadata<Book> hitsMetadata = searchResponse.hits();
        System.out.println("搜索到" + hitsMetadata.total().value() + "条数据");
        List<Hit<Book>> bookHitList = hitsMetadata.hits();
        for(int i=0;i<bookHitList.size();i++) {
            Hit<Book> bookHit = bookHitList.get(i);
            Book book = bookHit.source();
            System.out.println("文档[" + (i+1) + "]:" + book);
        }

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
